﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;

using AutoUpdaterDotNET;
namespace KDAcctAttach {

    public partial class FrmMain : Form {

        public FrmMain()
        {
            InitializeComponent();
        }

        private Dictionary<string, Form> _forms;

        #region 窗口载入

        private void FrmMain_Shown(object sender, EventArgs e)
        {
            _forms = new Dictionary<string, Form>();
            AddForm("tbAttach", new FrmAttach());
            AddForm("tbDetach", new FrmDetach());
            AddForm("tbSetting", new FrmSettings());
            AddForm("tbQuery", new FrmQuery());
            AddForm("tbTools", new FrmTools());
            tabMain.SelectedIndex = -1;
            tabMain.SelectedIndex = 0;
            Text += " ["+Assembly.GetExecutingAssembly().GetName().Version+"]";
            AutoUpdater.CheckForUpdateEvent += AutoUpdater_CheckForUpdateEvent;
            AutoUpdater.Start($"{Comm.GetUpdServer()}?{Guid.NewGuid().ToString().Replace("-", "")}");
        }

        private void AutoUpdater_CheckForUpdateEvent(UpdateInfoEventArgs args)
        {
            if (args is null)
                return;
            if(args.Error != null)
                MessageBox.Show(args.Error.Message);
            if(args.IsUpdateAvailable)
            {
                AutoUpdater.DownloadUpdate(args);
                Application.Exit();
            }
        }

        private void AddForm(string name, Form frm)
        {
            frm.TopLevel = false;
            frm.Dock = DockStyle.Fill;
            frm.FormBorderStyle = FormBorderStyle.None;
            _forms.Add(name, frm);
        }

        #endregion 窗口载入

        #region 选择标签

        private void TabMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabMain.SelectedIndex < 0)
                return;
            var tab = tabMain.TabPages[tabMain.SelectedIndex];
            ShowTab(tab);
        }

        private void ShowTab(TabPage tb)
        {
            var form = _forms[tb.Name];
            if (tb.Controls.Contains(form))
                return;
            tb.Controls.Add(form);
            form.Show();
        }

        #endregion 选择标签
    }
}